package cn.cht.controller;

import cn.cht.pojo.Token;
import cn.cht.pojo.User;
import cn.cht.service.AuthCodeService;
import cn.cht.service.TokenService;
import cn.cht.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/api/user")
@RefreshScope
public class UserController {

    public static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Reference(timeout = 10000)
    private AuthCodeService authCodeService;

    @GetMapping("/register/{email}/{password}/{code}")
    public Object register(HttpServletResponse response,
                           @PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code) {
        Integer result = authCodeService.validate(email, code);
        if (result == null || result == 1 || result == 2) {
            return 2;
        }

        if (userService.register(email, password) != null) {
            Token token = tokenService.save(email);
            Cookie tokenCookie = new Cookie("token", token.getToken());
            tokenCookie.setPath("/");
            Cookie emailCookie = new Cookie("email", email);
            emailCookie.setPath("/");
            response.addCookie(tokenCookie);
            response.addCookie(emailCookie);
            return 0;
        } else {
            return false;
        }
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email) {

        return userService.isRegistered(email) != null;
    }

    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response,
                        @PathVariable("email") String email, @PathVariable("password") String password) {
        User login = userService.login(email, password);
        if (login != null) {
            Token token = tokenService.save(email);
            Cookie tokenCookie = new Cookie("token", token.getToken());
            tokenCookie.setPath("/");
            Cookie emailCookie = new Cookie("email", email);
            emailCookie.setPath("/");
            response.addCookie(tokenCookie);
            response.addCookie(emailCookie);
            return login.getEmail();
        } else {
            return "false";
        }
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        return tokenService.info(token);
    }
}
